﻿(function () {
    "use strict";
    var i;
    WinJS.UI.Pages.define("/pages/groupedItems/groupedItems.html", {
        ready: function (element, options) {

            // bring focus to the listview
            listView.winControl.oniteminvoked = this._itemInvoked.bind(this);
            listView.winControl.element.focus();

            // attach event listeners for "add zip code"
            addZipCodeAppBarButton.addEventListener("click", this.showFlyout, false);
            addZipCodeButton.addEventListener("click", this.addZipCode.bind(this), false);

        },

        // update page layout in response to viewState changes
        updateLayout: function (element) {
        },

        _itemInvoked: function (args) {
            var item = Data.list.getAt(args.detail.itemIndex);
            WinJS.Navigation.navigate("/pages/itemDetail/itemDetail.html", { item: item });
        },

        showFlyout: function () {
            flyout.winControl.show(addZipCodeButton);
        },

        hideFlyout: function () {
            flyout.winControl.hide();
            listView.winControl.element.focus();
        },

        addZipCode: function () {
            var zip = tb_zipCode.value;

            Data.getBingData(zip).then(
                function (result) {
                    Data.list.dataSource.beginEdits();
                    Data.list.dataSource.insertAtEnd(null, result);
                    Data.list.dataSource.endEdits();
                    Data.saveSettings(result);

                    console.info('Success: getBingData()', zip, Debug.clock());
                    return result;
                },
                function (error) { console.error('Error: getBingData()', zip, Debug.clock()); });
            this.hideFlyout();
        }

    });
})();